package com.jvm123.blog.controller

import com.jvm123.blog.dao.ApiRepos
import com.jvm123.blog.service.CollectService
import com.jvm123.blog.service.MenuService
import com.jvm123.blog.service.PostService
import com.jvm123.blog.service.TermService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable

/**
 *
 * @author yawn
 *     2019/10/6 18:54
 */
@Controller
class IndexController {

    @Autowired
    ApiRepos apiRepos
    @Autowired
    MenuService menuService
    @Autowired
    PostService postService
    @Autowired
    CollectService collectService
    @Autowired
    TermService termService

    @GetMapping("index")
    void index(Model model) {
        setMenus(model)
        model.addAttribute("collects", collectService.findAll())
    }

    @GetMapping("home")
    void home(Model model) {
        setMenus(model)
        model.addAttribute("posts", postService.findTop())
        model.addAttribute("collects", collectService.findWithPosts())
    }

    @GetMapping("blogs")
    void blogs(Model model) {
        setMenus(model)
        model.addAttribute("posts", postService.findTop())
    }

    @GetMapping("series")
    String series(Model model) {
        findByType(model, "series")
        "index"
    }

    @GetMapping("videos")
    String videos(Model model) {
        findByType(model, "videos")
        "index"
    }

    @GetMapping("tools")
    String tools(Model model) {
        findByType(model, "tools")
        "index"
    }

    @GetMapping("tags")
    String tags(Model model) {
        setMenus(model)
        model.addAttribute("categories", termService.findCategories())
        model.addAttribute("tags", termService.findTags())
        "tags"
    }

    @GetMapping(["collect/{id}/{title}", "collect/{id}"])
    String collectDetail(@PathVariable("id") long id,
                         @PathVariable(value = "title", required = false) String title,
                         Model model) {
        setMenus(model)
        model.addAttribute("collect", collectService.findOne(id))
        "collectDetail"
    }

    private void findByType(Model model, String type) {
        setMenus(model)
        model.addAttribute("collects", collectService.findByType(type))
    }

    private void setMenus(Model model) {
        model.addAttribute("mainMenus", menuService.getMainMenu())
        model.addAttribute("topMenus", menuService.getTopMenu())
    }
}
